// vp_timer/pages/index/user.js
var app = getApp();
var vp = require('../../resource/js/vp.js');

Page({

        /**
         * 页面的初始数据
         */
        data: {
                _shareModal:false,
				showModal: false,
				showuserModal:false,
				message_num:0,
				isVip: false, // 是否会员
				userInfo: {
				      avatarUrl: 'https://banyetang.oss-cn-beijing.aliyuncs.com/xiaochengxu/avatar.jpg',
				      phone: '',
				      nickName: '',
					  gender:1
				    }
        },

        /**
         * 生命周期函数--监听页面加载
        */
        onLoad: function (options) {
			console.log(this);
			var self = this;  
			wx.setStorageSync('refresh_familydoctor',1)
        },


        onReady: function () {
        },

        /**
         * 生命周期函数--监听页面显示
         */
        onShow: function () {
			var self=this;
			wx.checkSession({
				success() { 
					console.log('succ')
					self.initData()
				},
				fail() { 
				  wx.login({
					success: (loginRes) => {
					  if (loginRes.code) {
						// 发送登录code到服务器获取session_key
						app.util.getUserInfo(function (response) {
							self.initData()
						});
					  }
					}
				  })
				}
			});
			
        },
		initData:function(){
			let self = this
			let aid = '';
			  if(!aid){
				  aid=wx.getStorageSync('VP_AID',2);
			  }
			app.mdInit(function (cfg,mine,area) {
				self.setData({
					cfg: cfg,
					mine:mine,
					area:area,
					main_loaded:true
				});
			
				self.main_load(false);
			},{
				aid:aid||2,
				fuid:'',
				stid:''
			},true);
		},
        /**
         * 生命周期函数--监听页面隐藏
         */
        onHide: function () {

        },

        /**
         * 生命周期函数--监听页面卸载
         */
        onUnload: function () {

        },

        /**
         * 分享
        */
       onShareAppMessage: function () {
			console.log(this.getSharePath());
			return {
				title: this.data.cfg.share_title?this.data.cfg.share_title:this.data.cfg.name,
				imageUrl: this.data.cfg.share_image_url,
				path: this.getSharePath()
			}
        },
        getSharePath:function(){
			var page = app.mdName + '/pages/index/index';
			var ps = '?aid='+this.data.area.id+'&fuid=' + this.data.mine.id
			return page + ps;
        },
        
        // 页面数据加载
        main_load(showLoading) {
			const self = this;
			app.util.request({
				url: 'User/index',
				showLoading: showLoading ? true : false,
				data: {
					m: app.mdName
				},
				complete(res) {
					wx.stopPullDownRefresh();
				},
				success(res) {
					var data = res.data.data;
					console.log(data);
					wx.setStorageSync('staffInfo',data.mine);
					
					self.setData({
						mine: data.mine,       
						statistic: data.statistic,
						staff: data.staff,
						isVip:data.mine.is_vip,
						message_num:data.message
					});
				}
			})
        },


        toProfile:function(){
			wx.navigateTo({
			  url: 'profile',
			})
        },
		// 续期会员
		renewMember: function() {
			wx.navigateTo({
				url: '/vp_pz/pages/familydoctor/subscribe?is_open=2'
			});
		},
		gomessage:function(){
			wx.navigateTo({ url: '/vp_pz/pages/user/messageList' });
		},
		gophysical:function(){
			wx.navigateTo({ url: '/vp_pz/pages/physicalExam/orderIndex/index' });
		},
		//家庭医生
		gofamilydoctor:function(){
			let vip = wx.getStorageSync('VIP_STASTUS')
			if (!vip) {
			  wx.navigateTo({ url: '/vp_pz/pages/familydoctor/membershipGuide' });
			} else {
			  wx.navigateTo({ url: '/vp_pz/pages/familydoctor/index' });
			}
		},
		
		//我是社区医护人员		
		checkcommunitydoctor:function(){
			const self = this;
			if(this.data.mine.type == 3){
				wx.redirectTo({
					url:'../communitydoctor/center'
				})
			}else{
				wx.redirectTo({
					url:'../communitydoctor/login'
				})
			}			
		},
		//我是管理员
		
		checkadmin:function(){
			const self = this;
			wx.redirectTo({
				url:'../admin/login'
			})		
		},
		// 我是陪诊师
		checkstaff:function(){
			const self = this;
			if(this.data.mine.type != 2){
				if(this.data.mine.type == 1){
					app.util.request({
					  url: 'Staff/getStaffInfo',
					  method: 'POST',
					  data: { user_id: this.data.mine.id },
					  success: (res) => {
					    if(res.data.data.code == 1){
					    	if(res.data.data.data.status == 10){
								wx.showToast({
									title:'请耐心等待平台审核'
								})
							}else if(res.data.data.data.status != 20){
								wx.showToast({
								  title: '请勿重复提交',
								  icon: 'none'
								})
							}else{
								wx.redirectTo({
									url:'../staff/index'
								})
							}
					    }else{
					    	self.setData({
					    		showModal: true,
					    	});
					    }
					  }
					})
					
				}else{
					wx.showToast({ title: '您已认证其他身份' })
				}
			}else{
				wx.redirectTo({
					url:'../staff/index'
				})
			}			
		},
		navigateToReg:function(){
			
			const self = this;
			self.setData({
			    showModal: false,
			});
			wx.redirectTo({
				url:'../staff/reg'
			})
		},
		hideModal:function(){
			this.setData({ showuserModal: false,showModal:false })
		},
		// 获取用户信息
		  getUserInfo() {
		    const self = this;
			
			wx.getUserProfile({
			  desc: '用于完善会员资料', // 声明用途
			  success: (res) => {
				this.setData({
				  'userInfo.gender': res.userInfo.gender
				})
			  },
			  fail: (err) => {
				console.error('获取失败:', err)
				wx.showToast({
				  title: '获取用户信息失败',
				  icon: 'none'
				})
			  }
			})
			  wx.login({
			    success: (loginRes) => {
					console.log(loginRes)
			      if (loginRes.code) {
			        // 发送登录code到服务器获取session_key
			        app.util.request({
			          url: 'User/gowxLogin',
			          method: 'POST',
			          data: { code: loginRes.code },
			          success: (res) => {
			            self.setData({ showuserModal: true })
			          }
			        })
			      }
			    }
			  })
		    
		  },
		  // 获取微信头像
		handleChooseAvatar(e) {
				try {
				    if (typeof e.detail === 'object' && e.detail.avatarUrl) {
				      // 正常情况
				      this.updateAvatar(e.detail.avatarUrl)
				    } else {
				      throw new Error('非标准返回格式')
				    }
				  } catch (err) {
				    console.error('获取头像失败:', err)
				    
				    // 降级方案
				    wx.showModal({
				      title: '提示',
				      content: '获取头像失败，是否尝试从相册选择？',
				      success: (res) => {
				        if (res.confirm) {
				          wx.chooseImage({
				            count: 1,
				            success: (res) => {
				              this.updateAvatar(res.tempFilePaths[0])
				            }
				          })
				        }
				      }
				    })
				}
		    },
		  updateAvatar(tempFilePath) {
			  const that = this
			  var url = app.util.url('Common/upload');
			  wx.uploadFile({
				url: url,
				filePath: tempFilePath,
				name: 'file',
				formData: {
					'path': tempFilePath
				},
				success: function (ret) {
					ret.data = JSON.parse(ret.data);
					console.log(ret.data);
			  
					if (ret.data.code!=1){
						wx.showModal({
							title: '头像上传失败',
							content: ret.data.message,
							showCancel:false,
							success(res) {
								that.setData({
									"userInfo.avatarUrl": ''
								});
							}
						});
					}else{
						that.setData({
							'userInfo.avatarUrl': ret.data.data.url
						});
					}
				}
			  });
			
		  },
		    // 获取用户昵称
		  // 昵称输入回调
		    onNickNameInput: function(e) {
		      this.setData({
		        'userInfo.nickName': e.detail.value
		      });
		    },
		    // 获取手机号
		    handleGetPhone(e) {
				const self = this
				console.log(e.detail)
		      if (e.detail.code) {
				  app.util.request({
					  url: 'User/decodePhone',
					  data: {
						code: e.detail.code,
						encryptedData:e.detail.encryptedData,
						iv:e.detail.iv
					  },
					  success: (res) => {
						if (res.data.data.success) {
						  self.setData({
							'userInfo.phone': res.data.data.phoneNumber
						  })
						  wx.showToast({ title: '手机号获取成功' })
						}
					  }
				  })
		      } else {
		        wx.showToast({ title: '获取手机号失败', icon: 'none' })
		      }
		    },
		  
		    // 提交信息
		handleSubmit() {
			const self = this
			if (!this.data.userInfo.avatarUrl || !this.data.userInfo.phone || !this.data.userInfo.nickName) {
				wx.showToast({ title: '请先完善信息', icon: 'none' })
				return
			}
			console.log(self.data.userInfo)
			//判断是否提交过申请
			let flag = 0;
			app.util.request({
			  url: 'Staff/getStaffInfo',
			  data: {},
			  success(res) {
				if(res.data.code && res.data.data.status !== 5){
					flag = 1
				}
			  }
			})
			if(flag == 1){
				app.util.request({
				  url: 'Staff/personReg',
				  data: {
					  m: app.mdName,
					  aid:self.data.area.id,
					  submit:'save',
					  avatarUrl:self.data.userInfo.avatarUrl,
					  phone:self.data.userInfo.phone,
					  nickName:self.data.userInfo.nickName,
					  gender:self.data.userInfo.gender,
				  },
				  success(res) {
					  wx.showModal({
						  title:'提交成功',
						  content: res.data.msg,
						  confirmText: '确定',
						  showCancel: false,
						  success:function(){
							  self.hideModal()
						  }
					  });
				  }
			  })
		  }else{
			  app.util.request({
			      url: 'User/profile',
			      data: {
					  m: app.mdName,
					  submit: 'save',
					  avatar:self.data.userInfo.avatarUrl,
					  nickname:self.data.userInfo.nickName
			      },
			      success(res) {
			          app.updateMine(function(mine){
			              self.setData({
			                  mine: mine
			              });
			              wx.showToast({
			                  title: res.data.msg,
			                  icon: 'success',
			                  duration: 2000,
			                  success: function () {
			                      self.setData({ showuserModal: false,showModal:false })
			                  }
			              });
			          });
			      }
			  });
			  
		  }
		},
        toOrders:function(e){
			app.orders_filt=e.currentTarget.dataset.filt?e.currentTarget.dataset.filt:0;
			wx.switchTab({
			  url: '../order/index',
			})
        },

        showShareModal(){
			this.setData({_shareModal:true});
        },
        
})